<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic Data Binding Example</title>
</head>
<body>
<template id="my-component-template">
    <style>
        .card {
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 30vw;
        }

        .card h2 {
            margin-top: 0;
        }

        .card button {
            padding: 10px;
            background-color: blue;
            color: white;
            border: none;
            cursor: pointer;
        }
    </style>
    <div class="card">
        <h2 id="title"></h2>
        <p id="content"></p>
        <button>More Info</button>
    </div>
</template>

<my-card title="Welcome" content="This is a welcome message."></my-card>


<script>
    class MyCard extends HTMLElement {
        static get observedAttributes() {
            return ['title', 'content'];
        }

        constructor() {
            super();
            const shadowRoot = this.attachShadow({ mode: 'open' });
            const template = document.getElementById('my-component-template').content.cloneNode(true);
            shadowRoot.appendChild(template);

            // 初始化属性值
            this.title = parseInt(this.getAttribute('title')) || 'Default Title';
            this.content = parseInt(this.getAttribute('content')) || 'Default Content';

            // 获取DOM元素
            this.titleEl = shadowRoot.querySelector('#title');
            this.contentEl = shadowRoot.querySelector('#content');
            this.render();

        }

        connectedCallback() {
            this.render();
        }

        attributeChangedCallback(name, oldValue, newValue) {
            if (name === 'title' || name === 'content') {
                this.render();
            }
        }

        render() {
            this.titleEl.textContent = this.title
            this.contentEl.textContent = this.content
        }
    }

    customElements.define('my-card', MyCard);

</script>

</body>
</html>
